package java_class_work.week07;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

/**
 * @Auther: admin
 * @Date: 2022/10/24 10:22
 * @Description:
 */

public class JDBC {
    // 本地连接：localhost 或 127.0.0.1 或 【空】
    // 端口号：3306
    // 数据库名：blog
    // 时区参数：serverTimezone=GMT
    // 关闭安全连接：useSSL=false
    // 防止中文乱码：characterEncoding=utf-8
    public static final String URL = "jdbc:mysql://localhost:3306/blog?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "123456";


    public static void main(String[] args) {
        // 获取配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("java_class_work\\week07\\jdbc");
        String driverClass = bundle.getString("driverClass");
        String url = bundle.getString("url");
        String username = bundle.getString("username");
        String password = bundle.getString("password");


        //连接对象
        Connection connection = null;
        // 数据库对象
        Statement statement = null;

        try {
            // 1. 注册驱动
            // 方式一：
//            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            // 方式二（推荐）：反射
            Class.forName(driverClass);

            // 2. 获取连接
            connection = DriverManager.getConnection(url, username, password);
//            System.out.println(connection);

            // 3. 获取数据库对象
            statement = connection.createStatement();

            // 4. 执行SQL
            String insert_sql = "insert into user values ('root','123456',0)";
            int rows = statement.executeUpdate(insert_sql);

            //5. 处理返回结果集
            System.out.println("effect rows " + rows);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6. 释放资源
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}
